package com.hson.demo.base.common;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

public class CheckCaseValidator implements ConstraintValidator<CheckCase, String> {

    private CaseMode caseMode;

    public void initialize(CheckCase constraintAnnotation) {
        this.caseMode = constraintAnnotation.value();
    }

    public boolean isValid(String object, ConstraintValidatorContext constraintContext) {

        if (object == null || object == "")
            return true;

    	object = object.toLowerCase().replaceAll("\\s+", " ").replace("&lt;", "<").replace("&gt;", ">");
        if (caseMode == CaseMode.NOSCRIPT) {
    		String regExHtml = "</?(?!script)([a-zA-Z]+)[^>]+>";
    		Pattern pHtml = Pattern.compile(regExHtml,Pattern.CASE_INSENSITIVE);
    		Matcher mHtml = pHtml.matcher(object);
    		object = mHtml.replaceAll(" "); //过滤html标签 
    		
        	String regex = ".*?<\\s*?script[^>]*?>.*?<\\s*?/script\\s*?>.*?";
        	boolean flag = object.matches(regex);
        	if (flag) {
        		return false;//如果有js 则验证失败
        	}
        } else if (caseMode == CaseMode.NOHTML) {
        	String regex = ".*?<\\s*([a-zA-Z]+)\\s*[^<]*?(?:/>|>.*?<\\s*/\\1\\s*>).*?";
        	boolean flag = object.matches(regex);
        	if (flag) {
        		return false;//如果有html 则验证失败
        	}
        }
		return true;
    }

}